package com.google.io.lastcall.gwt.countdownclock.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class EditNumber extends VerticalPanel {
	private int currentNumber=0;
	private Image UpButton=new Image("/images/UpButton.png");
	private Image DownButton=new Image("/images/DownButton.png");
	private Label MyNumber=new Label();
	private int mod=10;
	private int min=0;
	private MyHandler toStringHelper=null;
	public EditNumber(int defaultNumber,int mini,int max,final MyHandler handler,final MyHandler toString) {
		//add 100 to max so that it will make the length for 3 spaces
		this(defaultNumber,mini,max+100,handler);
		mod=max;
		toStringHelper=toString;
		changeNumber(currentNumber);
	}
	public EditNumber(int defaultNumber,int mini,int max,final MyHandler handler) {
		super();
		mod=max;
		min=mini;
		currentNumber=defaultNumber;
		int width=50*(Integer.toString(mod-1).length());
		MyNumber.setPixelSize(50*(Integer.toString(mod-1).length()), 50);
		MyNumber.addStyleName("EditableNumber");
		DownButton.setPixelSize(width, 50);
		UpButton.setPixelSize(width, 50);
		super.add(UpButton);
		super.add(MyNumber);
		super.add(DownButton);
		DownButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changeNumber(currentNumber-1);
				handler.send(Integer.toString(currentNumber));
			}
		});
		UpButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changeNumber(currentNumber+1);
				handler.send(Integer.toString(currentNumber));
			}
		});
		changeNumber(currentNumber);
	}
	public void changeNumber(int newNum) {
		currentNumber=newNum;
		if(currentNumber<min) {
			currentNumber=mod-1;
		} else if(currentNumber>=mod) {
			currentNumber=min;
		}
		MyNumber.setText(this.toString());
	}
	public int getNumber() {
		return currentNumber;
	}
	public void setMax(int max) {
		mod=max;
		changeNumber(currentNumber);
	}
	public String toString() {
		if(toStringHelper==null) {
			return Integer.toString(currentNumber);
		} else {
			return toStringHelper.send(Integer.toString(currentNumber));
		}
	}
}